package com.bxait.toymail.product.exception;
import com.bxait.com.exception.BizCodeEnum;
import com.bxait.com.exception.product.CheckOutException;
import com.bxait.com.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Chen
 * @description:  集中处理商品模块中所有的异常
 * @ClassName toyMailExceptionControllerAdvice
 * @create 2023-03-14 21:38
 * @Version 1.0
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.bxait.toymail.product.controller")
public class ToyMailExceptionControllerAdvice {

    /***
     * @param e
     * @==============History===============<br/>
     * @Description // TODO  处理校验异常
     * @Date 2023/3/14 21:42
     * @Author <a href="qq:2277411582@qq.com">chen</a>
     * @return com.bxait.com.utils.R
     */
    public R handleValidException(MethodArgumentNotValidException e){
        log.error("数据出现校验问题:{},异常类型：{}",e.getMessage(),e.getClass());
        // 出现的异常会在BindingResult中保存
        BindingResult bindingResult = e.getBindingResult();
        // 准备map返回异常信息
        Map<String,String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach((item)->{
            String field = item.getField();
            String message = item.getDefaultMessage();
            map.put(field,message);
        });
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMsg()).put("data",map);
    }


    /**
     * @param throwable
     * @==============History===============<br/>
     * @Description // TODO  处理自定义参数校验的异常
     * @Date 2023/3/15 22:18
     * @Author <a href="qq:2277411582@qq.com">chen</a>
     * @return com.bxait.com.utils.R
     */
    @ExceptionHandler(value = CheckOutException.class)
    public R checkOutException(CheckOutException throwable){
        log.error("数据出现校验问题:{},异常类型：{}",throwable.getMessage(),throwable.getClass());
        return R.error(BizCodeEnum.VALID_EXCEPTION.getCode(), throwable.getMessage());
    }

    /**
     * @param throwable
     * @==============History===============<br/>
     * @Description // TODO  处理最大的异常
     * @Date 2023/3/14 21:51
     * @Author <a href="qq:2277411582@qq.com">chen</a>
     * @return com.bxait.com.utils.R
     */
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        log.error("错误：",throwable);
        return R.error(BizCodeEnum.UNKNOWN_EXCEPTION.getCode(), BizCodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }
}
